<?php

namespace app\admin\command;

use app\admin\model\User;
use app\common\model\UserChangeLog;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\Db;
use app\admin\model\share\ShareUser;
use app\admin\model\exchange\Code;
use app\common\library\Auth;

class Canceluser extends Command
{
    protected function configure()
    {
        $this->setName('Canceluser')->setDescription("计划任务 Canceluser");
    }

    protected function execute(Input $input, Output $output)
    {
        $output->writeln('Date Crontab job start...');
        /*** 这里写计划任务列表集 START ***/

        $this->Canceluser();
       
        /*** 这里写计划任务列表集 END ***/
        $output->writeln('Date Crontab job end...');
    }

    // 扫码推广用户 用户3小时内不下单，自动删除关系（删除该用户）注册时间
    private function Canceluser()
    {
        // 查找所有没下单用户
        $time = time() - 900;
        $ShareUser =  (new ShareUser())->where('addtime','<=',$time)->where('user_id','>',1)->where(['amount'=>0, 'role'=>0])->select();
        foreach ($ShareUser as $key => &$value) {
            $parent_id = $value['parent_id'];
            $temp_lists = (new ShareUser())->where(['parent_id' => $value['user_id']])->select();
            $exchange_code = (new Code())->where(['user_id' => $value['user_id']])->select();
            if (empty($temp_lists) && empty($value['is_order']) && empty($exchange_code) && (empty($value['price']) || '0.000' == $value['price']) && empty($value['score'])) {
                $user_id = $value['user_id'];
                $users = User::get($value['user_id']);
                if (!empty($users)) {
                    $users['uid'] = $users['id'];
                    unset($users['id']);
                    Db::name("user_delete")->strict(false)->insert($users->toArray());
                }
                $share_user = $value;
                if (!empty($share_user)) {
                    $share_user['shareuserid'] = $share_user['id'];
                    unset($share_user['id']);
                    Db::name("share_user_delete")->strict(false)->insert($share_user->toArray());
                }
                $before_mobile = $users['mobile'];
                Auth::instance()->delete($value['user_id']);
                (new ShareUser())->where(['id' => $value['shareuserid']])->delete();
                UserChangeLog::create(['user_id' => $user_id, 'before_mobile' => $before_mobile, 'after_mobile' => 0, 'memo' => '直接删除用户']);
            }
           
            $temp_data = (new ShareUser())->where(['parent_id'=>$parent_id])->select();
            foreach ($temp_data as $key => $value) {
                $role_type = $key+1;
                (new ShareUser())->where(['id'=>$value['id']])->update(['role_type'=>$role_type]);
            }
        }
        echo date("Y-m-d H:i:s") . " 成功 \r\n";
    }
}
